package top.lingchen.bootwebadmin.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import top.lingchen.bootwebadmin.bean.User;

import javax.servlet.http.HttpSession;

/**
 * @Author 凌宸
 * @create 2021-12-07 下午 5:14
 * @Description
 * @Version 1.0
 */
@Controller
public class IndexController {

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 来登录页
     */
    @GetMapping(value = {"/", "/login"})
    public String loginPage(){
        return "login";
    }

    /**
     * 登录成功来到主页
     */
    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model){
        if(StringUtils.hasText(user.getUsername()) && StringUtils.hasLength(user.getPassword())){
            // 账号密码不为空，则登录成功，将用户信息写进 session
            session.setAttribute("loginUser", user);
            // 登录成功重定向到 main.html,重定向到 main页面，可以防止刷新时登录页面重复提交
            return "redirect:/main.html";
        }else{
            // 登陆失败，添加错误提示信息，并回到登录页面
            model.addAttribute("msg", "账号密码错误！");
            return "login";
        }
    }

    @GetMapping("/main.html")
    public String mainPage(HttpSession session, Model model){
//        // 是否登录，拦截器，过滤器
////        Object loginUser = session.getAttribute("loginUser");
////        if(loginUser != null){
////            return "main";
////        }else{
////            // 回到登录页面
////            model.addAttribute("msg", "请重新登录！");
////            return "login";
////        }

        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String mainCount = opsForValue.get("/main.html");
        String sqlCount = opsForValue.get("/sql");
        model.addAttribute("mainCount", mainCount);
        model.addAttribute("sqlCount", sqlCount);
        return "main";
    }
}
